﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.WorkItemTracking.Client;

namespace TFSTools.TFSLibrary
{
    public sealed class TFSStoredQueryDefinition : TFSServerEntity
    {
        private QueryDefinition serverQueryDefinition;
        private TFSTeamProject tfsTeamProject;

        internal TFSStoredQueryDefinition(ITFSConnection connection, QueryDefinition storedQuery, TFSTeamProject project)
            : base(connection)
        {
            this.serverQueryDefinition = storedQuery;
            this.tfsTeamProject = project;
        }

        public TFSTeamProject TeamProject { get { return this.tfsTeamProject; } }

        internal QueryDefinition ServerEntity { get { return this.serverQueryDefinition; } }

        public string Name { get { return this.serverQueryDefinition.Name; } }

        public string Path { get { return this.serverQueryDefinition.Path; } }

        public string QueryText { get { return this.serverQueryDefinition.QueryText; } }

        public override string ToString() { return this.serverQueryDefinition.ToString(); }
    }

    public sealed class TFSStoredQueryDefinitionCollection : TFSServerEntityCollection<TFSStoredQueryDefinition>
    {
        public TFSStoredQueryDefinitionCollection(ITFSConnection connection)
            : base(connection)
        {
        }

        public TFSStoredQueryDefinitionCollection(ITFSConnection connection, IList<TFSStoredQueryDefinition> list)
            : base(connection, list)
        {
        }

        public TFSStoredQueryDefinitionCollection(ITFSConnection connection, int capacity)
            : base(connection, capacity)
        {
        }

        internal static TFSStoredQueryDefinitionCollection Create(ITFSConnection connection, TFSTeamProject project)
        {
            var storeProject = connection.WorkItemStore.ServerEntity.Projects[project.Name];
            var queryHierarchy = storeProject.QueryHierarchy;

            var queryDefinitions = new TFSStoredQueryDefinitionCollection(connection);

            foreach (var queryItem in queryHierarchy)
            {
                project.GetQueries(queryDefinitions, (QueryFolder)queryItem);
            }

            return new TFSStoredQueryDefinitionCollection(connection, queryDefinitions);
        }
    }
}
